import { userLogin } from '@/api/system/login'
import { getCache, getToken, removeCache, removeToken, setCache, setToken } from '@/utils/cookie'
import { defineStore } from 'pinia'

const key = 'info'

export const userStore = defineStore('user', () => {
  let userInfo = {}

  function login (loginUser) {
    return new Promise((resolve, reject) => {
      userLogin(loginUser).then(response => {
        setCache(key, JSON.stringify(loginUser))
        const data = response.data.data
        userInfo = data
        setToken(JSON.stringify(data))
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  }
  function getCacheInfo () {
    return new Promise(resolve => {
      let data = getToken()
      if (data) {
        data = JSON.parse(data)
        userInfo = data
      }
      resolve(userInfo)
    })
  }
  function getInfo () {
    return new Promise((resolve, reject) => {
      const data = getToken()
      if (data) {
        userInfo = JSON.parse(data)
        resolve(userInfo)
        return
      }
      const userInfoCache = getCache(key)
      if (!userInfoCache) {
        resolve(userInfoCache)
        return
      }
      const loginUser = JSON.parse(userInfoCache)
      userLogin(loginUser)
        .then(response => {
          const data = response.data.data
          userInfo = data
          setToken(JSON.stringify(data))
          resolve(userInfo)
        }).catch(error => {
          reject(error)
        })
    })
  }
  function logout () {
    return new Promise(resolve => {
      userInfo = {}
      removeToken()
      removeCache(key)
      resolve(userInfo)
    })
  }

  return { userInfo, login, getInfo, logout, getCacheInfo }
})
